package database

import (
	"demo/models"

	"github.com/sirupsen/logrus"
)

func InsertOneUser(user *models.Userinfo) error {
	_, err := engine.InsertOne(user)
	if err!=nil{
		return err
	}
	user_profile:=&models.UserProfile{
		Id:user.Id,
		Name: user.Name,
		ContactInfo: user.ContactInfo,
		Address: user.Address,
	}
	_, err = engine.InsertOne(user_profile)
	if err!=nil{
		return err
	}
	ele_info:=&models.EleInfo{
		Id:user.Id,
		EleSum: 0,
		EleStatus: "未欠费",
		EleBalance: 0,
		EleUsemoney: 0,
	}
	_, err = engine.InsertOne(ele_info)
	return err
}

func GetUserinfoByUsername(username string) (*models.Userinfo, error) {
	user := &models.Userinfo{
		Username: username,
	}
	exist, err := engine.Where("username = ?", username).Get(user)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	if !exist {
		return nil, ErrNotFound
	}
	return user, nil
}

func GetUserinfoByEmail(email string) (*models.Userinfo, error) {
	user := &models.Userinfo{
		Email: email,
	}
	exist, err := engine.Where("email = ?", email).Get(user)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	if !exist {
		return nil, ErrNotFound
	}
	return user, nil
}

func GetUserinfoByUserId(userId int) (*models.Userinfo, error) {
	user := &models.Userinfo{
		Id: userId,
	}
	exist, err := engine.Where("id = ?", userId).Get(user)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	if !exist {
		return nil, ErrNotFound
	}
	return user, nil
}

func GetAllUserinfo() ([]*models.Userinfo, error) {
	var users []*models.Userinfo
	err := engine.Find(&users)
	if err != nil {
		logrus.Errorln(err)
		return nil, err
	}
	return users, nil
}


func UpdateUserinfo(user *models.Userinfo, cols ...string) error {
	_, err := engine.Where("id = ?", user.Id).Cols(cols...).Update(user)
	if err != nil {
		return err
	}
	user_profile:=&models.UserProfile{
		Id:user.Id,
		Name: user.Name,
		ContactInfo: user.ContactInfo,
		Address: user.Address,
	}
	_, err = engine.Where("id = ?", user_profile.Id).Cols(cols...).Update(user_profile)
	return err
}


func GetUserEleInfo(userId int) (*models.EleInfo, error){
	ele_info := &models.EleInfo{
		Id: userId,
	}
	exist, err := engine.Where("id = ?", userId).Get(ele_info)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	if !exist {
		return nil, ErrNotFound
	}
	return ele_info, nil
}

//获取最新的用户用电报告
func GetLatestReport(userId int) (*models.UsageReports, error) {
	userReport := &models.UsageReports{}

	exist, err := engine.Where("id = ?", userId).Desc("report_date").Limit(1).Get(userReport)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	if !exist {
		return nil, ErrNotFound
	}
	return userReport, nil
}
